package com.erlinyou.im.web.controller.base;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.coobird.thumbnailator.Thumbnails;


public class DownloadImages {
//implements Callable<List<BufferedImage>> 
/*	private List<String> urlPath;

	public List<String> getUrlPath(){
		return this.urlPath;
	}

	public void setUrlPath(List<String> urlPath){
		this.urlPath = urlPath;
	}*/
	private static Logger logger = LoggerFactory.getLogger(DownloadImages.class);
//	public static void main(String[] args) throws Exception {
//		System.out.println(download("https://ss0.baidu.com/73x1bjeh1BF3odCf/it/u=2349566611,2614992701&fm=85").getWidth());
//	}
	public static BufferedImage download(String urlPath) throws Exception{
		return ImageIO.read(new URL(urlPath));
	}
/*
	@Override
	public List<BufferedImage> call() {
		try {
			return downloads(getUrlPath());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
*/


	public static List<BufferedImage> downloads(List<String> urlPath) throws Exception{
		return urlPath.stream().map(url -> {
			try {
				if(urlPath.size()==5) {
					BufferedImage convertImage = scaleByPercentage(Thumbnails.of(ImageIO.read(new URL(url))).size(62,62).outputQuality(1).outputFormat("jpg").asBufferedImage(), 65, 65);
					return convertImage = convertCircular(convertImage,65);
					//	return Thumbnails.of(ImageIO.read(new URL(url))).size(62,62).outputQuality(1).outputFormat("jpg").asBufferedImage();
				}
				BufferedImage convertImage = scaleByPercentage(Thumbnails.of(ImageIO.read(new URL(url))).size(84,84).outputQuality(1).outputFormat("jpg").asBufferedImage(), 84, 84);
				return convertImage = convertCircular(convertImage,87);
			} catch (Exception e) {
				logger.error("downloads error:",e);
				return null;
			}
		}).collect(Collectors.toList());
	}
	
	private static  ExecutorService executorService = Executors.newFixedThreadPool(10);
	public static List<BufferedImage> zdownloads(List<String> urlPath) throws Exception{
		return urlPath.stream().map(url -> {
			dowImg dowImg = new dowImg();
			dowImg.setUrl(url);
			if(urlPath.size()==5) {
				dowImg.setSize1(62);
				dowImg.setSize2(65);
			}else {
				dowImg.setSize1(84);
				dowImg.setSize2(84);
			}
			Future<BufferedImage> downloadimg = executorService.submit(dowImg);
			try {
				BufferedImage convertImage = downloadimg.get();
				if(urlPath.size()==5) {
					return convertImage = convertCircular(convertImage,65);
				}else {
					return convertImage = convertCircular(convertImage,87);
				}
			} catch (InterruptedException | ExecutionException | IOException e) {
				e.printStackTrace();
				return null;
			}
		}).collect(Collectors.toList());
	}

//    /**
//     * @param args
//     * @throws Exception
//     */
//
//    public InputStream download(String urlPath) throws Exception {
//        // ����URL
//        URL url = new URL(urlPath);
//        // ������
//        URLConnection con = url.openConnection();
//        //��������ʱΪ5s
//        con.setConnectTimeout(5*1000);
//        // ������
//        InputStream is = con.getInputStream();
//        // 1K�����ݻ���
//        byte[] bs = new byte[1024];
//        // ��ȡ�������ݳ���
//        int len;
//        // ������ļ���
////        File sf=new File(savePath);
////        if(!sf.exists()){
////            sf.mkdirs();
////        }
////        int randomNo=(int)(Math.random()*1000000);
////        String filename=urlPath.substring(urlPath.lastIndexOf("/")+1,urlPath.length());//��ȡ��������ͼƬ������
////        filename=new java.text.SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())+randomNo+filename;//ʱ��+�������ֹ�ظ�
////        OutputStream os = new FileOutputStream(sf.getPath()+"\\"+filename);
////        String virtualPath="/upload/SDSPage/"+filename;//�������ݿ������·��
//        // ��ʼ��ȡ
////        while ((len = is.read(bs)) != -1) {
////            os.write(bs, 0, len);
////        }
////        // ��ϣ��ر���������
//        return is;
//    }
		public static BufferedImage convertCircular(BufferedImage bi1,int imgsize) throws IOException {
		//		BufferedImage bi1 = ImageIO.read(new File(url));
				
				// 这种是黑色底的
		//		BufferedImage bi2 = new BufferedImage(bi1.getWidth(), bi1.getHeight(), BufferedImage.TYPE_INT_RGB);
		 
				// 透明底的图片
			RenderingHints renderingHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
			renderingHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
				BufferedImage bi2 = new BufferedImage(bi1.getWidth(), bi1.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
				Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, bi1.getWidth(), bi1.getHeight());
				Graphics2D g2 = bi2.createGraphics();
				g2.setClip(shape);
				// 使用 setRenderingHint 设置抗锯齿
				g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
				g2.drawImage(bi1, 0, 0, null);
				// 设置颜色
				g2.setBackground(Color.white);
				int border = 1;
				 //画笔是4.5个像素，BasicStroke的使用可以查看下面的参考文档
	            //使画笔时基本会像外延伸一定像素，具体可以自己使用的时候测试
	            Stroke s = new BasicStroke(4.5F, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
	            g2.setStroke(s);
	            g2.setColor(Color.WHITE);
	            g2.drawOval(border, border, imgsize - border * 2, imgsize - border * 2);
				g2.dispose();
//				return bi2;
		///	 BufferedImage avatarImage = ImageIO.read(new URL(url));
		/*
		 * int width = 65; // 透明底的图片 BufferedImage bi11 = new BufferedImage(width,
		 * width, BufferedImage.TYPE_4BYTE_ABGR); Graphics2D graphics =
		 * bi1.createGraphics(); //把图片切成一个圓 {
		 * graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
		 * RenderingHints.VALUE_ANTIALIAS_ON); //留一个像素的空白区域，这个很重要，画圆的时候把这个覆盖 int border
		 * = 1; //图片是一个圆型 Ellipse2D.Double shape = new Ellipse2D.Double(border, border,
		 * width - border * 2, width - border * 2); //需要保留的区域 graphics.setClip(shape);
		 * graphics.drawImage(bi11, border, border, width - border * 2, width - border *
		 * 2, null); graphics.dispose(); }
		 */
		/*
		 * //在圆图外面再画一个圆 { //新创建一个graphics，这样画的圆不会有锯齿 // g2 = bi1.createGraphics();
		 * g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
		 * RenderingHints.VALUE_ANTIALIAS_ON); int border = 3;
		 * //画笔是4.5个像素，BasicStroke的使用可以查看下面的参考文档 //使画笔时基本会像外延伸一定像素，具体可以自己使用的时候测试 Stroke
		 * s = new BasicStroke(4.5F, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
		 * g2.setStroke(s); g2.setColor(Color.WHITE); g2.drawOval(border, border, 65 -
		 * border * 2, 65 - border * 2); g2.dispose(); }
		 */
				return bi2;
			
			}
		
		public static BufferedImage scaleByPercentage(BufferedImage inputImage, int newWidth, int newHeight) throws Exception {
			// 获取原始图像透明度类型
			int type = inputImage.getColorModel().getTransparency();
			int width = inputImage.getWidth();
			int height = inputImage.getHeight();
			// 开启抗锯齿
			RenderingHints renderingHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
			// 使用高质量压缩
			renderingHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
			BufferedImage img = new BufferedImage(newWidth, newHeight, type);
			Graphics2D graphics2d = img.createGraphics();
			graphics2d.setRenderingHints(renderingHints);
			graphics2d.drawImage(inputImage, 0, 0, newWidth, newHeight, 0, 0, width, height, null);
			graphics2d.dispose();
			return img;
		}

}

class dowImg implements Callable<BufferedImage>{
	private String url;
	private int size1;
	private int size2;
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	
	public int getSize1() {
		return size1;
	}
	public void setSize1(int size1) {
		this.size1 = size1;
	}
	public int getSize2() {
		return size2;
	}
	public void setSize2(int size2) {
		this.size2 = size2;
	}
	@Override
	public BufferedImage call() throws Exception {
		BufferedImage convertImage = DownloadImages.scaleByPercentage(Thumbnails.of(ImageIO.read(new URL(url))).size(size1,size1).outputQuality(1).outputFormat("jpg").asBufferedImage(), size2, size2);
		return convertImage;
	}
}